package org.opencv.SDK;

import java.util.ArrayList;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;

public class ColorLabeler {
    private String[] colorNames = {"blue", "green", "red"};
    private Mat[] labMat;
    private Mat[] rgbMat;

    public ColorLabeler() {
        Mat[] matArr = new Mat[3];
        this.rgbMat = matArr;
        this.labMat = new Mat[3];
        matArr[0] = new Mat(1, 1, CvType.CV_8UC3, new Scalar(0.0d, 0.0d, 255.0d));
        this.rgbMat[1] = new Mat(1, 1, CvType.CV_8UC3, new Scalar(0.0d, 255.0d, 0.0d));
        this.rgbMat[2] = new Mat(1, 1, CvType.CV_8UC3, new Scalar(255.0d, 0.0d, 0.0d));
        for (int i = 0; i < 3; i++) {
            this.labMat[i] = new Mat();
            Imgproc.cvtColor(this.rgbMat[i], this.labMat[i], 45);
        }
    }

    public String label(Mat mat, MatOfPoint matOfPoint) {
        ArrayList arrayList = new ArrayList();
        arrayList.add(matOfPoint);
        Mat zeros = Mat.zeros(mat.rows(), mat.cols(), 0);
        Imgproc.drawContours(zeros, arrayList, -1, new Scalar(255.0d, 255.0d, 255.0d), -1);
        Imgproc.erode(zeros, zeros, Imgproc.getStructuringElement(0, new Size(3.0d, 3.0d)), new Point(-1.0d, -1.0d), 2);
        Mat mat2 = new Mat(1, 1, CvType.CV_8UC3, Core.mean(mat, zeros));
        double d = 2.147483647E9d;
        int i = 0;
        for (int i2 = 0; i2 < 3; i2++) {
            double norm = Core.norm(this.labMat[i2], mat2);
            if (norm < d) {
                i = i2;
                d = norm;
            }
        }
        return this.colorNames[i];
    }
}
